package com.onepower.admin.controller;


import com.onepower.core.domain.response.SysMenuInfo;
import com.onepower.core.exception.BizException;
import com.onepower.core.modules.repository.entity.SysMenu;
import com.onepower.core.modules.service.ISysMenuService;
import com.onepower.core.result.BizResultCode;
import com.onepower.core.result.CommonResult;
import com.onepower.core.utils.ResultUtils;
import com.onepower.core.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author kin
 * @since 2018-08-01
 */
@RestController
@RequestMapping("/api/sys/menu")
public class SysMenuController {
    @Autowired
    private ISysMenuService sysMenuService;

    @RequestMapping(value = "getUserMenuList", method = RequestMethod.GET)
    public CommonResult getUserMenuList() {
        List<SysMenuInfo> userMenuList = sysMenuService.getUserMenuList(SecurityUtils.getCurrentUserId());
        return ResultUtils.ok(userMenuList);
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResult list() {
        List<SysMenuInfo> list = sysMenuService.getMenuList(true);
        return ResultUtils.ok(list);
    }

    @RequestMapping(value = "listMenu", method = RequestMethod.GET)
    public CommonResult listMenu() {
        List<SysMenuInfo> listMenu = sysMenuService.getMenuList(false);
        return ResultUtils.ok(listMenu);
    }

    @RequestMapping("/info/{menuId}")
    public CommonResult info(@PathVariable("menuId") Long menuId) {
        SysMenu sysMenu = sysMenuService.getById(menuId);
        return ResultUtils.ok(sysMenu);
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public CommonResult save(@RequestBody SysMenu sysMenu) {
        sysMenu.setCreateUserId(SecurityUtils.getCurrentUserId());
        sysMenuService.save(sysMenu);
        return ResultUtils.ok();
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public CommonResult update(@RequestBody SysMenu sysMenu) {
        if(sysMenu.getParentId().equals(sysMenu.getId())){
            throw new BizException(BizResultCode.PARENT_ID_IS_NO_EQUAL_SELF);
        }
        sysMenuService.updateById(sysMenu);
        return ResultUtils.ok();
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public CommonResult delete(@RequestBody Integer[] menuIds) {
        sysMenuService.removeByIds(Arrays.asList(menuIds));
        return ResultUtils.ok();
    }
}
